/**
 * 全局状态管理器
 * 管理应用的全局状态、数据流和状态同步
 */

import { reactive, ref, computed, watch } from 'vue'

/**
 * 状态类型枚举
 */
export const STATE_TYPES = {
	// 用户状态
	USER: 'user',
	SETTINGS: 'settings',
	PREFERENCES: 'preferences',
	
	// 应用状态
	APP: 'app',
	THEME: 'theme',
	LANGUAGE: 'language',
	NETWORK: 'network',
	
	// 游戏状态
	GAME: 'game',
	TEST_HISTORY: 'testHistory',
	ACHIEVEMENTS: 'achievements',
	STATISTICS: 'statistics',
	
	// UI状态
	UI: 'ui',
	MODAL: 'modal',
	LOADING: 'loading',
	NOTIFICATION: 'notification'
}

/**
 * 默认状态
 */
const DEFAULT_STATE = {
	[STATE_TYPES.USER]: {
		id: null,
		name: '',
		avatar: '',
		level: 1,
		experience: 0,
		isLoggedIn: false,
		lastLoginTime: null,
		totalPlayTime: 0
	},
	
	[STATE_TYPES.SETTINGS]: {
		theme: 'light',
		language: 'zh-CN',
		sound: true,
		vibration: true,
		notifications: true,
		autoSave: true,
		difficulty: 'medium',
		animations: true,
		reducedMotion: false
	},
	
	[STATE_TYPES.PREFERENCES]: {
		defaultTestType: 'memory',
		showTips: true,
		showProgress: true,
		autoStart: false,
		countdownDuration: 3,
		dailyGoal: 5,
		reminderTime: '20:00',
		dataCollection: true
	},
	
	[STATE_TYPES.APP]: {
		version: '1.0.0',
		isFirstLaunch: true,
		lastUpdateTime: null,
		installTime: null,
		launchCount: 0,
		currentPage: 'home',
		previousPage: null,
		isOnline: true,
		deviceInfo: null
	},
	
	[STATE_TYPES.THEME]: {
		currentTheme: 'light',
		customThemes: {},
		colors: {},
		isDarkMode: false,
		followSystem: false
	},
	
	[STATE_TYPES.LANGUAGE]: {
		currentLanguage: 'zh-CN',
		availableLanguages: ['zh-CN', 'en-US'],
		localeData: {},
		fallbackLanguage: 'zh-CN'
	},
	
	[STATE_TYPES.NETWORK]: {
		isOnline: true,
		connectionType: 'wifi',
		networkSpeed: 'fast',
		lastOnlineTime: null,
		offlineQueue: []
	},
	
	[STATE_TYPES.GAME]: {
		currentTest: null,
		testInProgress: false,
		currentLevel: 1,
		currentScore: 0,
		bestScores: {},
		streak: 0,
		longestStreak: 0,
		totalTests: 0,
		todayTests: 0
	},
	
	[STATE_TYPES.TEST_HISTORY]: {
		records: [],
		lastTestTime: null,
		totalRecords: 0,
		memoryRecords: [],
		reactionRecords: [],
		chimpRecords: [],
		visualRecords: [],
		typingRecords: []
	},
	
	[STATE_TYPES.ACHIEVEMENTS]: {
		unlocked: [],
		progress: {},
		lastUnlocked: null,
		totalUnlocked: 0,
		categories: {
			beginner: 0,
			intermediate: 0,
			advanced: 0,
			master: 0
		}
	},
	
	[STATE_TYPES.STATISTICS]: {
		overall: {
			totalTests: 0,
			totalTime: 0,
			averageScore: 0,
			bestScore: 0,
			accuracy: 0
		},
		byType: {},
		trends: {},
		lastUpdated: null
	},
	
	[STATE_TYPES.UI]: {
		loading: false,
		loadingText: '',
		modals: {},
		toasts: [],
		bottomSheet: null,
		navigationVisible: true,
		statusBarHeight: 0,
		safeAreaInsets: { top: 0, bottom: 0, left: 0, right: 0 }
	},
	
	[STATE_TYPES.MODAL]: {
		active: null,
		queue: [],
		data: {},
		options: {}
	},
	
	[STATE_TYPES.LOADING]: {
		global: false,
		page: false,
		component: {},
		api: {},
		message: ''
	},
	
	[STATE_TYPES.NOTIFICATION]: {
		list: [],
		unreadCount: 0,
		lastNotification: null,
		settings: {
			enabled: true,
			sound: true,
			vibration: true,
			badge: true
		}
	}
}

/**
 * 状态管理器类
 */
class StateManager {
	constructor() {
		this.state = reactive(this.deepClone(DEFAULT_STATE))
		this.listeners = new Map()
		this.middleware = []
		this.history = []
		this.maxHistorySize = 50
		this.persistKeys = new Set([
			STATE_TYPES.USER,
			STATE_TYPES.SETTINGS,
			STATE_TYPES.PREFERENCES,
			STATE_TYPES.THEME,
			STATE_TYPES.LANGUAGE,
			STATE_TYPES.GAME,
			STATE_TYPES.TEST_HISTORY,
			STATE_TYPES.ACHIEVEMENTS,
			STATE_TYPES.STATISTICS
		])
		
		this.init()
	}
	
	/**
	 * 初始化状态管理器
	 */
	init() {
		this.loadPersistedState()
		this.setupWatchers()
		this.setupAutoSave()
		this.initializeApp()
	}
	
	/**
	 * 加载持久化状态
	 */
	loadPersistedState() {
		try {
			if (typeof uni !== 'undefined') {
				for (const key of this.persistKeys) {
					const saved = uni.getStorageSync(`state_${key}`)
					if (saved) {
						this.state[key] = { ...this.state[key], ...saved }
					}
				}
			}
		} catch (error) {
			console.error('加载持久化状态失败:', error)
		}
	}
	
	/**
	 * 设置状态监听器
	 */
	setupWatchers() {
		// 监听需要持久化的状态变化
		for (const key of this.persistKeys) {
			watch(
				() => this.state[key],
				(newValue) => {
					this.persistState(key, newValue)
				},
				{ deep: true }
			)
		}
		
		// 监听主题变化
		watch(
			() => this.state[STATE_TYPES.THEME].currentTheme,
			(newTheme) => {
				this.emit('themeChanged', newTheme)
			}
		)
		
		// 监听语言变化
		watch(
			() => this.state[STATE_TYPES.LANGUAGE].currentLanguage,
			(newLanguage) => {
				this.emit('languageChanged', newLanguage)
			}
		)
		
		// 监听网络状态变化
		watch(
			() => this.state[STATE_TYPES.NETWORK].isOnline,
			(isOnline) => {
				this.emit('networkChanged', isOnline)
			}
		)
	}
	
	/**
	 * 设置自动保存
	 */
	setupAutoSave() {
		// 每5分钟自动保存一次
		setInterval(() => {
			if (this.state[STATE_TYPES.SETTINGS].autoSave) {
				this.saveAllState()
			}
		}, 5 * 60 * 1000)
	}
	
	/**
	 * 初始化应用状态
	 */
	initializeApp() {
		// 更新启动次数
		this.setState(STATE_TYPES.APP, {
			launchCount: this.state[STATE_TYPES.APP].launchCount + 1,
			lastUpdateTime: new Date().toISOString()
		})
		
		// 设置安装时间（仅首次）
		if (this.state[STATE_TYPES.APP].isFirstLaunch) {
			this.setState(STATE_TYPES.APP, {
				installTime: new Date().toISOString(),
				isFirstLaunch: false
			})
		}
		
		// 获取设备信息
		this.updateDeviceInfo()
		
		// 检查网络状态
		this.updateNetworkStatus()
	}
	
	/**
	 * 获取状态
	 * @param {string} type - 状态类型
	 * @param {string} key - 状态键（可选）
	 * @returns {any} 状态值
	 */
	getState(type, key = null) {
		if (!this.state[type]) {
			console.warn(`状态类型不存在: ${type}`)
			return null
		}
		
		if (key) {
			return this.state[type][key]
		}
		
		return this.state[type]
	}
	
	/**
	 * 设置状态
	 * @param {string} type - 状态类型
	 * @param {Object|string} keyOrData - 键名或数据对象
	 * @param {any} value - 值（当第二个参数是键名时）
	 */
	setState(type, keyOrData, value = undefined) {
		if (!this.state[type]) {
			console.warn(`状态类型不存在: ${type}`)
			return
		}
		
		// 记录历史
		this.recordHistory(type, this.deepClone(this.state[type]))
		
		// 执行中间件
		const action = {
			type: 'SET_STATE',
			stateType: type,
			payload: typeof keyOrData === 'string' ? { [keyOrData]: value } : keyOrData,
			timestamp: Date.now()
		}
		
		const processedAction = this.runMiddleware(action)
		if (!processedAction) return
		
		// 更新状态
		if (typeof keyOrData === 'string') {
			this.state[type][keyOrData] = value
		} else {
			Object.assign(this.state[type], keyOrData)
		}
		
		// 触发监听器
		this.emit(`${type}Changed`, this.state[type])
		this.emit('stateChanged', { type, data: this.state[type] })
	}
	
	/**
	 * 重置状态
	 * @param {string} type - 状态类型
	 */
	resetState(type) {
		if (!this.state[type] || !DEFAULT_STATE[type]) {
			console.warn(`无法重置状态类型: ${type}`)
			return
		}
		
		this.recordHistory(type, this.deepClone(this.state[type]))
		this.state[type] = reactive(this.deepClone(DEFAULT_STATE[type]))
		this.emit(`${type}Reset`, this.state[type])
	}
	
	/**
	 * 批量更新状态
	 * @param {Object} updates - 更新对象
	 */
	batchUpdate(updates) {
		const batchAction = {
			type: 'BATCH_UPDATE',
			payload: updates,
			timestamp: Date.now()
		}
		
		const processedAction = this.runMiddleware(batchAction)
		if (!processedAction) return
		
		Object.entries(updates).forEach(([type, data]) => {
			if (this.state[type]) {
				this.recordHistory(type, this.deepClone(this.state[type]))
				Object.assign(this.state[type], data)
				this.emit(`${type}Changed`, this.state[type])
			}
		})
		
		this.emit('batchUpdated', updates)
	}
	
	/**
	 * 计算属性
	 * @param {Function} getter - 计算函数
	 * @returns {ComputedRef} 计算属性引用
	 */
	computed(getter) {
		return computed(() => getter(this.state))
	}
	
	/**
	 * 添加中间件
	 * @param {Function} middleware - 中间件函数
	 */
	addMiddleware(middleware) {
		if (typeof middleware === 'function') {
			this.middleware.push(middleware)
		}
	}
	
	/**
	 * 运行中间件
	 * @param {Object} action - 动作对象
	 * @returns {Object|null} 处理后的动作
	 */
	runMiddleware(action) {
		let processedAction = action
		
		for (const middleware of this.middleware) {
			try {
				processedAction = middleware(processedAction, this.state)
				if (!processedAction) {
					return null // 中间件阻止了动作
				}
			} catch (error) {
				console.error('中间件执行失败:', error)
			}
		}
		
		return processedAction
	}
	
	/**
	 * 记录历史
	 * @param {string} type - 状态类型
	 * @param {any} state - 状态快照
	 */
	recordHistory(type, state) {
		this.history.unshift({
			type,
			state,
			timestamp: Date.now()
		})
		
		// 限制历史记录大小
		if (this.history.length > this.maxHistorySize) {
			this.history = this.history.slice(0, this.maxHistorySize)
		}
	}
	
	/**
	 * 撤销操作
	 * @param {string} type - 状态类型
	 * @returns {boolean} 是否成功撤销
	 */
	undo(type) {
		const historyItem = this.history.find(item => item.type === type)
		if (!historyItem) {
			return false
		}
		
		this.state[type] = reactive(this.deepClone(historyItem.state))
		this.emit(`${type}Restored`, this.state[type])
		return true
	}
	
	/**
	 * 添加事件监听器
	 * @param {string} event - 事件名称
	 * @param {Function} listener - 监听器函数
	 */
	on(event, listener) {
		if (!this.listeners.has(event)) {
			this.listeners.set(event, [])
		}
		this.listeners.get(event).push(listener)
	}
	
	/**
	 * 移除事件监听器
	 * @param {string} event - 事件名称
	 * @param {Function} listener - 监听器函数
	 */
	off(event, listener) {
		if (!this.listeners.has(event)) return
		
		const listeners = this.listeners.get(event)
		const index = listeners.indexOf(listener)
		if (index > -1) {
			listeners.splice(index, 1)
		}
	}
	
	/**
	 * 触发事件
	 * @param {string} event - 事件名称
	 * @param {any} data - 事件数据
	 */
	emit(event, data) {
		if (!this.listeners.has(event)) return
		
		const listeners = this.listeners.get(event)
		listeners.forEach(listener => {
			try {
				listener(data)
			} catch (error) {
				console.error(`事件监听器执行失败 ${event}:`, error)
			}
		})
	}
	
	/**
	 * 持久化状态
	 * @param {string} key - 状态键
	 * @param {any} value - 状态值
	 */
	persistState(key, value) {
		try {
			if (typeof uni !== 'undefined' && this.persistKeys.has(key)) {
				uni.setStorageSync(`state_${key}`, value)
			}
		} catch (error) {
			console.error(`持久化状态失败 ${key}:`, error)
		}
	}
	
	/**
	 * 保存所有状态
	 */
	saveAllState() {
		for (const key of this.persistKeys) {
			this.persistState(key, this.state[key])
		}
	}
	
	/**
	 * 清除所有状态
	 */
	clearAllState() {
		try {
			if (typeof uni !== 'undefined') {
				for (const key of this.persistKeys) {
					uni.removeStorageSync(`state_${key}`)
				}
			}
			
			// 重置为默认状态
			Object.keys(DEFAULT_STATE).forEach(key => {
				this.state[key] = reactive(this.deepClone(DEFAULT_STATE[key]))
			})
			
			this.emit('stateCleared')
		} catch (error) {
			console.error('清除状态失败:', error)
		}
	}
	
	/**
	 * 更新设备信息
	 */
	updateDeviceInfo() {
		try {
			if (typeof uni !== 'undefined') {
				const systemInfo = uni.getSystemInfoSync()
				this.setState(STATE_TYPES.APP, {
					deviceInfo: {
						platform: systemInfo.platform,
						model: systemInfo.model,
						system: systemInfo.system,
						version: systemInfo.version,
						screenWidth: systemInfo.screenWidth,
						screenHeight: systemInfo.screenHeight,
						pixelRatio: systemInfo.pixelRatio
					}
				})
				
				// 更新安全区域
				this.setState(STATE_TYPES.UI, {
					statusBarHeight: systemInfo.statusBarHeight || 0,
					safeAreaInsets: systemInfo.safeAreaInsets || { top: 0, bottom: 0, left: 0, right: 0 }
				})
			}
		} catch (error) {
			console.error('更新设备信息失败:', error)
		}
	}
	
	/**
	 * 更新网络状态
	 */
	updateNetworkStatus() {
		try {
			if (typeof uni !== 'undefined') {
				uni.getNetworkType({
					success: (res) => {
						const isOnline = res.networkType !== 'none'
						this.setState(STATE_TYPES.NETWORK, {
							isOnline,
							connectionType: res.networkType,
							lastOnlineTime: isOnline ? new Date().toISOString() : this.state[STATE_TYPES.NETWORK].lastOnlineTime
						})
						
						// 同步应用状态
						this.setState(STATE_TYPES.APP, { isOnline })
					}
				})
				
				// 监听网络状态变化
				uni.onNetworkStatusChange((res) => {
					this.setState(STATE_TYPES.NETWORK, {
						isOnline: res.isConnected,
						connectionType: res.networkType,
						lastOnlineTime: res.isConnected ? new Date().toISOString() : this.state[STATE_TYPES.NETWORK].lastOnlineTime
					})
					
					this.setState(STATE_TYPES.APP, { isOnline: res.isConnected })
				})
			}
		} catch (error) {
			console.error('更新网络状态失败:', error)
		}
	}
	
	/**
	 * 深度克隆对象
	 * @param {any} obj - 要克隆的对象
	 * @returns {any} 克隆后的对象
	 */
	deepClone(obj) {
		if (obj === null || typeof obj !== 'object') {
			return obj
		}
		
		if (obj instanceof Date) {
			return new Date(obj.getTime())
		}
		
		if (obj instanceof Array) {
			return obj.map(item => this.deepClone(item))
		}
		
		if (typeof obj === 'object') {
			const cloned = {}
			for (const key in obj) {
				if (obj.hasOwnProperty(key)) {
					cloned[key] = this.deepClone(obj[key])
				}
			}
			return cloned
		}
		
		return obj
	}
	
	/**
	 * 获取状态快照
	 * @returns {Object} 状态快照
	 */
	getSnapshot() {
		return this.deepClone(this.state)
	}
	
	/**
	 * 导出状态
	 * @returns {Object} 导出的状态数据
	 */
	exportState() {
		const exportData = {}
		for (const key of this.persistKeys) {
			exportData[key] = this.deepClone(this.state[key])
		}
		return {
			data: exportData,
			version: this.state[STATE_TYPES.APP].version,
			exportTime: new Date().toISOString()
		}
	}
	
	/**
	 * 导入状态
	 * @param {Object} importData - 导入的状态数据
	 * @returns {boolean} 是否导入成功
	 */
	importState(importData) {
		try {
			if (!importData.data) {
				return false
			}
			
			Object.entries(importData.data).forEach(([key, value]) => {
				if (this.persistKeys.has(key) && this.state[key]) {
					this.state[key] = reactive({ ...this.state[key], ...value })
				}
			})
			
			this.emit('stateImported', importData)
			return true
		} catch (error) {
			console.error('导入状态失败:', error)
			return false
		}
	}
	
	/**
	 * 获取状态统计信息
	 * @returns {Object} 统计信息
	 */
	getStats() {
		return {
			totalStates: Object.keys(this.state).length,
			persistedStates: this.persistKeys.size,
			historySize: this.history.length,
			listenerCount: Array.from(this.listeners.values()).reduce((sum, arr) => sum + arr.length, 0),
			middlewareCount: this.middleware.length,
			lastUpdate: this.state[STATE_TYPES.APP].lastUpdateTime
		}
	}
	
	/**
	 * 销毁状态管理器
	 */
	destroy() {
		this.saveAllState()
		this.listeners.clear()
		this.middleware = []
		this.history = []
	}
}

// 创建全局实例
const stateManager = new StateManager()

// 便捷方法
export const getState = (type, key) => {
	return stateManager.getState(type, key)
}

export const setState = (type, keyOrData, value) => {
	stateManager.setState(type, keyOrData, value)
}

export const resetState = (type) => {
	stateManager.resetState(type)
}

export const batchUpdate = (updates) => {
	stateManager.batchUpdate(updates)
}

export const useComputed = (getter) => {
	return stateManager.computed(getter)
}

export const onStateChange = (event, listener) => {
	stateManager.on(event, listener)
}

export const offStateChange = (event, listener) => {
	stateManager.off(event, listener)
}

export const addStateMiddleware = (middleware) => {
	stateManager.addMiddleware(middleware)
}

export const undoState = (type) => {
	return stateManager.undo(type)
}

export const getStateSnapshot = () => {
	return stateManager.getSnapshot()
}

export const exportStateData = () => {
	return stateManager.exportState()
}

export const importStateData = (data) => {
	return stateManager.importState(data)
}

export const clearAllStates = () => {
	stateManager.clearAllState()
}

export const getStateStats = () => {
	return stateManager.getStats()
}

// 导出状态类型和默认状态
export { DEFAULT_STATE }

// 导出管理器实例
export default stateManager